<template>
	<view class="regPage">
		<scroll-view class="scroll-wrapper" scroll-y>
			<view class="form-box">
				<view class="pat-box">
					<view class="pat-title">
						<view class="">访客人脸核验照片<span class="heavy">*</span></view>
						<view class="title-tips">为确保预约顺利通过，请上传或拍摄本人照片</view>
						<view class="title-tips">（注：访客信息预约失效后，图片将自动删除）</view>

					</view>
					<view class="pat-img-box" @click="handleClick">
						<view class="pat-img-item-Uploaded" v-if="imageUrl">
							<image :src="imageUrl" mode="widthFix" alt="已选择的图片"></image>
						</view>
						<view class="pat-img-item" v-else>
							<image src="../../static/icon/icon-6.png" mode="" alt="默认图标"></image>
						</view>
						<view class="pat-tips">拍摄照片</view>
					</view>
					<ImageSelectorVue ref="imageSelectorRef" upload-url="/resource/oss/upload"
						@imageSelected="onImageSelected" @uploadSuccess="onUploadSuccess"
						@uploadFailed="onUploadFailed" />
				</view>
				<!-- 列表 -->
				<view class="from-item">
					<view class="">
						<view class="form-title">您的姓名<span class="heavy">*</span></view>
						<view class="">
							<uv-input placeholder="您的姓名" border="bottom" class="force-style-input"
								placeholderStyle="font-weight: normal;" color="#333" fontSize="16px"
								:customStyle="inputCustomStyle" v-model="fromVisitorList.visitorName"></uv-input>
						</view>
					</view>
					<view class="">
						<view class="form-title">联系电话<span class="heavy">*</span></view>
						<view class="">
							<uv-input placeholder="您的联系电话" border="bottom" class="force-style-input" color="#333"
								fontSize="16px" :customStyle="inputCustomStyle" type="number" maxlength="11"
								placeholderStyle="font-weight: normal;"
								v-model="fromVisitorList.visitorPhone"></uv-input>
						</view>
					</view>
					<picker mode="selector" :range="certificateTypes" range-key="label"
						@change="handleCertificateChange">
						<view class="user-input">
							<view class="form-title">访客证件类型<span class="heavy">*</span></view>
							<view class="selected-value">
								<text :class="{ 
					          'default-text': !selectedItem,
					          'selected-text': selectedItem 
					        }">
									{{ selectedItem?.label || '请选择访客证件类型' }}
								</text>
								<uv-icon name="arrow-right" color="#999" size="16" class="arrow-icon" />
							</view>
						</view>
					</picker>
					<view class="">
						<view class="form-title">证件号码<span class="heavy">*</span></view>
						<view class="">
							<uv-input placeholder="填写证件号码" border="bottom" class="force-style-input"
								placeholderStyle="font-weight: normal;" color="#333" fontSize="16px"
								:customStyle="inputCustomStyle" maxlength="18"
								v-model="fromVisitorList.visitorCardNumber"></uv-input>
						</view>
					</view>
					<picker mode="selector" :range="ReasonTypes" range-key="label" @change="handlePurposeVisit">
						<view class="user-input">
							<view class="form-title">来访事由<span class="heavy">*</span></view>
							<view class="selected-value">
								<text :class="{ 
					          'default-text': !selectedReason,
					          'selected-text': selectedReason 
					        }">
									{{ selectedReason?.label || '请选择来访事由' }}
								</text>
								<uv-icon name="arrow-right" color="#999" size="16" class="arrow-icon" />
							</view>
						</view>
					</picker>

					<view class="">
						<view class="form-title">来访时间<span class="heavy">*</span></view>
						<!-- 新增 restrictToCurrentTimeLater 属性，限制为当前时间之后 -->
						<DatetimePicker v-model="selectedDatetime" @confirm="onDatetimeConfirm"
							format="YYYY-MM-DD HH:mm" :restrictToTodayAndFuture="true"
							:restrictToCurrentTimeLater="true" />
					</view>
					<view class="">
						<view class="form-title">结束时间<span class="heavy">*</span></view>
						<!-- 结束时间保持不变 -->
						<DatetimePicker v-model="selectedEndDatetime" @confirm="onDatetimeEndConfirm"
							format="YYYY-MM-DD HH:mm" :restrictToTodayAndFuture="true" />
					</view>

					<view class="">
						<view class="form-title">随访人数</view>
						<view class="">
							<uv-input placeholder="请输入随访人数(上限30人)" border="bottom" class="force-style-input"
								color="#333" fontSize="16px" :customStyle="inputCustomStyle" @blur="changeblur"
								type="number" placeholderStyle="font-weight: normal;"
								v-model="fromVisitorList.visitorPeopleNumber" maxlength="30"></uv-input>
						</view>
					</view>
					<view class="">
						<view class="form-title">车牌号</view>
						<view class="plate-container">
							<!-- 循环渲染输入框行 -->
							<view class="plate-item" v-for="(item, index) in plateItems" :key="item.id">
								<view class="">
									<uv-input placeholder="请输入车牌号" border="none" class="force-style-input" color="#333"
										fontSize="16px" :customStyle="inputCustomStyle"
										placeholderStyle="font-weight: normal;" v-model="item.plateNumber"
										@blur="handlePlateChange">
									</uv-input>
								</view>
								<!-- 操作按钮 -->
								<view class="plus-item" @click="handleOperation(index)">
									<uv-icon :name="index === 0 ? 'plus' : 'close'" color="#fff" size="14">
									</uv-icon>
								</view>
							</view>
						</view>



					</view>
				</view>
			</view>

			<!-- 底部留白，确保最后一项能完全显示 -->
			<view class="bottom-padding"></view>
		</scroll-view>

		<view class="sub-item" @click="handelSubmit">
			<view class="sub-btn">提交申请</view>
		</view>

		<!-- 随访人数弹窗 -->
		<uv-popup ref="visitPopup" class="custom-popup " style="z-index: 99;" round="10px" :closeOnClickOverlay="false">
			<view class="visit-popup">
				<view class="visit-title">
					填写随访人信息
					<view class="visit-x-x" @click="closeCustomPopup">
						<uv-icon name="close-circle" size="28px"></uv-icon>
					</view>
				</view>
				<scroll-view scroll-y="true" style="max-height: 70vh; ">
					<view class="visit-from" v-for="(item, index) in fromVisitorList.followPeopleList" :key="index">
						<view class="user-input">
							<view class="">姓名：</view>
							<view class="">
								<uv-input :placeholder="`随访人${index + 1}姓名(必填)`" color="#333" fontSize="16px"
									border="none" inputAlign="right" v-model="item.visitorName">
								</uv-input>
							</view>
						</view>
						<view class="user-input" style="border: none;">
							<view class="">证件号码：</view>
							<view class="">
								<uv-input :placeholder="`随访人${index + 1}证件号(必填)`" color="#333" fontSize="16px"
									border="none" inputAlign="right" type="number" maxlength="18"
									v-model="item.visitorCardNumber">
								</uv-input>
							</view>
						</view>
					</view>
					<view class="form-follow-up">
						<view class="NextStep" @click="confirmVisitInfo">确定</view>
					</view>
				</scroll-view>
			</view>



		</uv-popup>

	</view>
</template>

<script setup>
	import {
		ref,
		watch
	} from 'vue'
	import {
		onLoad
	} from '@dcloudio/uni-app';
	import {
		$get,
		$post
	} from "@/utils/request.js"
	import {
		convertDepartmentsPublic,
		validatePhone,
		validateIdCard
	} from '@/utils/verifyMethod.js'
	import {
		useStore
	} from 'vuex'
	import CustomPickerVue from '@/components/CustomPicker/CustomPicker.vue'; //下拉选择
	import DatetimePicker from '@/components/DatetimePicker/DatetimePicker.vue'
	import ImageSelectorVue from '@/components/ImageSelector/ImageSelector.vue';


	const store = useStore()
	onLoad((options) => {
		if (options.paramsStr) {
			const paramsStr = decodeURIComponent(options.paramsStr);
			const paramsObj = JSON.parse(paramsStr);
			fromVisitorList.value = {
				...fromVisitorList.value, // 保留原有所有字段
				...paramsObj
			};

		}
		departmentList()
	});
	//1访客 2被访客 3保安
	watch(
		() => store.getters.getRoles,
		(newgetRoles) => {
			if (Array.isArray(newgetRoles) && newgetRoles.length > 0) {
				if (newgetRoles[0] == '2') {
					uni.switchTab({
						url: '/pages/index/index'
					})

				}
			}
		}, {
			deep: true,
			immediate: true,
		}
	);

	//输入框
	const inputCustomStyle = ref({
		padding: '12px 0',
		fontSize: '16px',
		fontWeight: '600',
		color: '#333',

	})


	// 身份证类型列表查询
	const certificateTypes = ref([]);
	const selectedItem = ref(null);
	const handleCertificateChange = (e) => {
		const selectedIndex = e.detail.value;
		selectedItem.value = certificateTypes.value[selectedIndex];
		fromVisitorList.value.visitorCardType = selectedItem.value.id;
	}
	// 来访事由列表查询
	const ReasonTypes = ref([]);
	const selectedReason = ref(null);
	const handlePurposeVisit = (e) => {
		const selectedIndex = e.detail.value;
		selectedReason.value = ReasonTypes.value[selectedIndex];
		fromVisitorList.value.reason = selectedReason.value.id;
	}
	// 查询身份证 来访事由字典
	const departmentList = () => {
		$get('/system/dict/data/type/visitor_card_type').then(res => { //身份证类型列表
			const news = convertDepartmentsPublic(res.data)
			certificateTypes.value = news
		})
		$get('/system/dict/data/type/visitor_reason').then(res => { //来访事由类型列表
			const news = convertDepartmentsPublic(res.data)
			ReasonTypes.value = news
		})

		const {
			nickName,
			idCardNumber,
			idCardType,
			idCardTypeName,
			phonenumber
		} = store.getters.getUserInfo
		fromVisitorList.value.visitorName = nickName
		fromVisitorList.value.visitorPhone = phonenumber
		fromVisitorList.value.visitorCardNumber = idCardNumber
		if (idCardType && idCardTypeName) {
			selectedItem.value = {
				id: idCardType,
				label: idCardTypeName
			};
		}
		fromVisitorList.value.visitorCardType = idCardType

	}


	// 选中的来访时间 Number(new Date())
	const selectedDatetime = ref(null);
	const onDatetimeConfirm = (timestamp, formatted) => {
		fromVisitorList.value.visitorBeginDate = formatted
	};
	// 选中的结束时间
	const selectedEndDatetime = ref(null);
	const onDatetimeEndConfirm = (timestamp, formatted) => {
		fromVisitorList.value.visitorEndDate = formatted
	};

	// 随访人数弹窗
	const visitPopup = ref(null)
	const visitNumber = ref(null)
	const changeblur = (value) => {
		const inputValue = value.detail?.value || value;
		const num = parseInt(inputValue, 10);

		// 先判断是否为有效数字且大于0
		if (!isNaN(num) && num > 0) {
			// 新增：判断是否超过30，超过则阻止后续操作
			if (num > 30) {
				uni.showToast({
					icon: 'none',
					title: "随访人不能超过30人"
				})
				fromVisitorList.value.visitorPeopleNumber = ''
				return;
			}

			// 重置随访人列表
			fromVisitorList.value.followPeopleList = [];
			// 根据输入数量初始化随访人列表
			for (let i = 0; i < num; i++) {
				fromVisitorList.value.followPeopleList.push({
					visitorName: '',
					visitorCardNumber: ''
				});
			}
			visitNumber.value = num;

			if (visitPopup.value) {
				visitPopup.value.open('');
			}
		} else {
			fromVisitorList.value.followPeopleList = [];
		}
	};

	// 随访人确定按钮点击事件
	const confirmVisitInfo = () => {
		// 关闭弹窗等操作
		if (visitPopup.value) {
			visitPopup.value.close();
		}
	};
	// 关闭弹窗
	const closeCustomPopup = () => {
		visitPopup.value.close();
	}

	// 车牌号添加（带唯一ID）
	const plateItems = ref([{
		plateNumber: '',
		id: Date.now()
	}]);

	// 处理添加/删除操作
	const handleOperation = (index) => {
		if (index === 0) {
			plateItems.value.push({
				plateNumber: '',
				id: Date.now()
			});
		} else {
			plateItems.value.splice(index, 1);
		}
		updateCarNumbers();
	};

	// 输入框内容变化时更新拼接结果
	const handlePlateChange = () => {
		updateCarNumbers();
	};

	// 更新车牌号拼接结果
	const updateCarNumbers = () => {
		// 过滤空值并拼接非空车牌号
		const carNumbers = plateItems.value
			.map(item => item.plateNumber.trim())
			.filter(Boolean); // 过滤空字符串
		fromVisitorList.value.visitorCarNumber = carNumbers.join(',');
	};


	// 图片路径
	const imageUrl = ref('');
	// 子组件引用
	const imageSelectorRef = ref(null);
	// 点击事件触发子组件
	const handleClick = () => {
		imageSelectorRef.value?.openImageSelector();
	};
	// 图片选择成功回调
	const onImageSelected = (path) => {
		// console.log('图片选择成功:', path);
	};
	// 上传成功回调
	const onUploadSuccess = (result) => {
		imageUrl.value = result.data.url;
		fromVisitorList.value.ossId = result.data.ossId

	};
	// 上传失败回调
	const onUploadFailed = (error) => {
		imageUrl.value = '';
	};


	// 提交整个表单
	const fromVisitorList = ref({
		ossId: '', // 图片id
		visitorName: '', // 访客姓名
		visitorPhone: '', // 访客联系电话
		visitorCardType: '', // 证件类型
		visitorCardNumber: '', // 证件号码
		reason: '', // 来访事由
		visitorBeginDate: '', // 开始时间
		visitorEndDate: '', // 结束时间
		visitorPeopleNumber: '', // 随访人数
		visitorCarNumber: '', // 车辆数
		followPeopleList: []
	});
	const validateForm = () => {
		const form = fromVisitorList.value;
		// 验证顶层必填字段
		const requiredFields = [
			'ossId',
			'visitorName',
			'visitorPhone',
			'visitorCardType',
			'visitorCardNumber',
			'reason',
			'visitorBeginDate',
			'visitorEndDate',
		];

		for (const field of requiredFields) {
			if (!form[field]) {
				uni.showToast({
					icon: 'none',
					title: `请填写${getFieldLabel(field)}`
				});
				return false;
			}
		}

		// 验证时间范围：结束时间不能早于开始时间
		const beginTime = new Date(form.visitorBeginDate).getTime();
		const endTime = new Date(form.visitorEndDate).getTime();
		if (endTime < beginTime) {
			uni.showToast({
				icon: 'none',
				title: '结束时间不能早于开始时间'
			});
			return false;
		}

		// 单独验证手机号格式（11位数字）
		if (!validatePhone(form.visitorPhone)) {
			uni.showToast({
				icon: 'none',
				title: '请输入11位数字的手机号码'
			});
			return false;
		}

		if (!validateIdCard(form.visitorCardNumber)) {
			uni.showToast({
				icon: 'none',
				title: '请输入18位的证件号码'
			});
			return false;
		}
		const inputValue = form.visitorPeopleNumber;
		const num = parseInt(inputValue, 10);
		if (num > 0) {
			//验证随访人信息是否正确
			const showValidationError = (index, field) => {
				uni.showToast({
					icon: 'none',
					title: `请填写随访人${index + 1}的${field}`
				});
			};
			for (const [i, person] of fromVisitorList.value.followPeopleList.entries()) {
				// 验证姓名
				if (!person.visitorName.trim()) {
					showValidationError(i, '姓名');
					visitPopup.value.open('');
					return false;
				}
				// 验证证件号码
				if (!person.visitorCardNumber.trim()) {
					showValidationError(i, '证件号码');
					visitPopup.value.open('');
					return false;
				}
				// 验证身份证号是否为18位
				if (person.visitorCardNumber.trim().length !== 18) {
					uni.showToast({
						icon: 'none',
						title: `随访人${i + 1}的证件号码必须为18位`
					});
					visitPopup.value.open('');
					return false;
				}
			}
		}
		visitPopup.value.close('');
		return true;
	};

	const getFieldLabel = (fieldName) => {
		const labels = {
			ossId: '上传本人照片',
			visitorName: '访客姓名',
			visitorPhone: '访客联系电话',
			visitorCardType: '证件类型',
			visitorCardNumber: '证件号码',
			reason: '来访事由',
			visitorBeginDate: '开始时间',
			visitorEndDate: '结束时间',
		};
		return labels[fieldName] || fieldName;
	};



	// 在提交函数中使用验证
	const handelSubmit = () => {
		if (validateForm()) {
			$post('/system/visitorInfo/add',
				fromVisitorList.value
			).then(res => {
				
				if (res.code == 200) {
					resetForm();
					uni.showToast({
						icon: 'success',
						title: '提交成功'
					})

					setTimeout(() => {
						uni.setStorageSync('needCloseFlag', true)
						uni.switchTab({
							url: `/pages/index/index`
						})
					}, 1500)



				} else {
					uni.showToast({
						icon: 'success',
						title: res.msg
					})
				}

			})
		}
	};

	// 重置表单函数
	const resetForm = () => {
		fromVisitorList.value = {
			ossId: '', // 图片id清空
			visitorName: '', // 访客姓名清空
			visitorPhone: '', // 访客联系电话清空
			visitorCardType: '', // 证件类型清空
			visitorCardNumber: '', // 证件号码清空
			reason: '', // 来访事由清空
			visitorBeginDate: '', // 开始时间清空
			visitorEndDate: '', // 结束时间清空
			visitorPeopleNumber: '', // 随访人数清空
			visitorCarNumber: '', // 车辆数清空
			// 重置随访人员列表为一个空对象
			followPeopleList: [{
				visitorName: '',
				visitorCardNumber: ''
			}]
		};

		// 同时重置车牌号输入框（如果需要）
		plateItems.value = [{
			plateNumber: '',
			id: Date.now()
		}];
	};
</script>

<style lang="scss">
	.regPage {
		width: 100vw;
		min-height: 100vh;
		background-color: #eff4fb;
		padding-bottom: 80px;
		box-sizing: border-box;
	}

	/* 仅添加滚动容器样式，不改变原有布局 */
	.scroll-wrapper {
		width: 100%;
		height: 100vh;
		box-sizing: border-box;
	}

	.form-box {
		padding: 20px;
		box-sizing: border-box;
	}

	.heavy {
		color: red;
		font-size: var(--font-16);
	}

	.pat-box {
		width: 100%;
		height: auto;
		background-color: #fff;
		border-radius: 10px;

		.pat-title {
			padding: 20px;
			box-sizing: border-box;
			color: var(--color-666);
			font-size: var(--font-16);

			.title-tips {
				color: red;
				font-size: 12px;
				margin: 4px;
			}

		}

		.pat-img-box {
			width: 100%;
			height: auto;
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;
			gap: 10px;
			padding-bottom: 20px;
			box-sizing: border-box;

			.pat-img-item-Uploaded {
				width: 140px;
				height: 140px;
				display: flex;
				align-items: center;
				justify-content: center;
				overflow: hidden;

				image {
					width: 100%;
					height: 100%;
					object-fit: cover;
				}
			}


			.pat-img-item {
				width: 90px;
				height: 90px;

				image {
					width: 100%;
					height: 100%;
				}
			}

			.pat-tips {
				color: var(--color-666);
				font-size: var(--font-14);
			}
		}

	}

	.from-item {
		width: 100%;
		margin: 20px 0;
		background-color: #fff;
		border-radius: 10px;
		padding: 20px;
		box-sizing: border-box;
		display: flex;
		flex-direction: column;
		gap: 20px;

		.user-input {
			width: 100%;
			// height: 30px;
			padding: 16px 0px;
			box-sizing: border-box;
			display: flex;
			flex-direction: column;
			gap: 10px;
			// align-items: center;
			// justify-content: space-between;
			border-bottom: 1px solid #d5d5d5;
			color: var(--color-333);

			.form-title {
				color: var(--color-666);
				font-size: var(--font-16);
			}


			.selected-value {
				display: flex;
				align-items: center;
				justify-content: space-between;
				gap: 6px;

				.default-text {
					color: var(--color-999);
				}

				.selected-text {
					font-size: var(--font-16);
					font-weight: 600;
					color: var(--color-333);
				}
			}

		}


		.form-title {
			color: var(--color-666);
			font-size: var(--font-16);

		}

		.plate-item {
			width: 100%;
			display: flex;
			align-items: center;
			justify-content: space-between;
			border-bottom: 1px solid #dadbde;

			.plus-item {
				width: 36px;
				height: 22px;
				background-color: #2b74e2;
				border-radius: 4px;
				display: flex;
				justify-content: center;
				align-items: center;
			}

		}

		.certificate {
			width: 100%;
			padding: 10px 8px;
			display: flex;
			justify-content: space-between;
			border-bottom: 1px solid #DADBDE;
		}

		::v-deep .input-placeholder {
			color: #999 !important;

		}
	}

	.visit-popup {
		width: 90vw;
		max-height: 80vh;
		padding: 30px;
		box-sizing: border-box;

		.visit-title {
			font-size: var(--font-18);
			color: var(--color-333);
			font-weight: bold;
			position: relative;

			.visit-x-x {
				position: absolute;
				top: 0;
				right: 0;
				transform: translate(50%, -50%);
			}
		}


		.visit-from {
			width: 100%;
			height: auto;
			margin-top: 20px;
			background-color: #F8F8F8;
			border-radius: 10px;
			padding: 10px;
			box-sizing: border-box;

			.user-input {
				width: 100%;
				display: flex;
				align-items: center;
				justify-content: space-between;
				padding: 10px 0px;
				box-sizing: border-box;
				border-bottom: 1px solid #d5d5d5;
			}
		}

		.form-follow-up {
			margin-top: 20px;
			display: flex;
			flex-direction: column;
			gap: 10px;



			.NextStep {
				width: 100%;
				height: 50px;
				text-align: center;
				line-height: 50px;
				color: var(--color-ff);
				font-size: var(--font-16);
				background-color: #2b74e2;
				border-radius: 50px;
				font-weight: 600;
			}


		}
	}

	.sub-item {
		width: 100%;
		height: 100px;
		position: fixed;
		bottom: 0;
		left: 0;
		z-index: 99;
		background-color: #fff;
		padding-bottom: constant(safe-area-inset-bottom);
		padding-bottom: env(safe-area-inset-bottom);
		box-sizing: border-box;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;

		.sub-btn {
			width: 80%;
			height: 40px;
			text-align: center;
			line-height: 40px;
			background-color: #2b74e2;
			border-radius: 50px;
			color: var(--color-ff);
			font-size: var(--font-16);
		}
	}

	/* 底部留白确保最后一项可见 */
	.bottom-padding {
		height: 30px;

	}
</style>